package cn.wjssl.domain.strategy.service.rule.chain.factory;

import cn.wjssl.domain.strategy.model.entity.StrategyEntity;
import cn.wjssl.domain.strategy.repository.IStrategyRepository;
import cn.wjssl.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author：lxd
 * @Description 责任链装配工厂
 * @Date：2025/2/10
 */

@Slf4j
@Service
public class DefaultChainFactory {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private Map<String, ILogicChain> logicChainMap;

    /**
     * 装配责任链
     * @param strategyId
     * @return
     */
    public ILogicChain openLogicChain(Long strategyId) {
        // 查询 strategy 获取 rule_models
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels2Array();
        // 如果该策略没有配置 rule_model, 那直接用默认抽奖
        if (ruleModels == null || ruleModels.length == 0) return logicChainMap.get(LogicModel.RULE_DEFAULT.getCode());

        // 初始化ILogicChain
        ILogicChain logicChain = logicChainMap.get(ruleModels[0]);
        ILogicChain current = logicChain;
        // 遍历,装配链表
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextChain = logicChainMap.get(ruleModels[i]);
            current = current.appendNext(nextChain);
        }
        // 最后装配默认抽奖方式, 防止出错
        current.appendNext(logicChainMap.get(LogicModel.RULE_DEFAULT.getCode()));
        return logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 当前奖品ID - 内部流转使用 */
        private Integer awardId;
        /** 当前奖品标题 - 内部流转使用 */
        private String awardTitle;
        /** 奖品配置信息 */
        private String awardConfig;
        /** 奖品顺序号 */
        private Integer sort;
        /** 当前过滤规则 rule_default, rule_blacklist, rule_weight - 根绝过滤规则的不同, 确定后续流程 */
        private String logicModel;
    }

    // 前置抽奖过滤规则类型【rule_default - 默认抽奖、rule_blacklist - 黑名单过滤、rule_weight - 权重抽奖】
    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }
}
